package org.example.handler;

import lombok.extern.slf4j.Slf4j;
import org.example.domain.User;
import org.example.service.UserService;
import org.example.utils.JwtUtil;
import org.example.utils.ResponseUtil;
import org.example.utils.Result;
import org.example.utils.SecurityContextUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

@Component
@Slf4j
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String account = String.valueOf(request.getParameter("account"));
        User user = (User) userService.findUserByAccount(account).getData();

        String permissions = user.getAdmin() == 0 ? "ROLE_normal" : "ROLE_admin" ;
        String token = JwtUtil.createToken(user.getId(),user.getAccount(),permissions);

        response.setHeader("Authorization",token);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        log.info("用户: [{}] 登录成功!!! , 权限为: [{}]",account , permissions);
        // SecurityContextHolder 赋值,用于授权
        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(user.getAccount(),token,
                        AuthorityUtils.commaSeparatedStringToAuthorityList(permissions))
        );
        ResponseUtil.out(response,Result.success(token));
    }
}
